package com.etone.smartaudit.wopi.config;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Configuration
public class WopiInterceptConfig implements WebMvcConfigurer {


    @Value("${wopi.digst}")
    private String digst;

    @Bean
    public CustomerIntercept getIntercept() {

        return new CustomerIntercept();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getIntercept()).addPathPatterns("/files/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    class CustomerIntercept implements HandlerInterceptor {
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        }

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //验证是否有权限访问文件
            //遍历获取所有参数

            try {
                Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
                Map<String, String[]> params = request.getParameterMap();
                StringBuilder md5Key = new StringBuilder();
                if (pathVariables != null) {
                    String fileName = (String) pathVariables.get("name");
                    md5Key.append(fileName);
                }
                params.forEach((k, v) -> {
                    if (!k.equals("key")) {
                        md5Key.append(v[0]);
                    }
                });
//                String key = request.getParameter("key");
//                String flag = SecureUtil.md5(md5Key.append(digst).toString());
//                if (key != null && !flag.equals(key)) {
//                    response.setContentType("application/json;charset=utf-8");
//                    response.getWriter().write("你没有访问权限");
//                    return false;
//                } else {
////                logger.info("test redis import :" + stringRedisTemplate.opsForValue().get(key));
//                    // TODO 验证逻辑
//                    return true;
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
    }
}
